import React from 'react';
import { Upload, Modal, message, Button } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import oss from '@/utils/oss/index';
import sty from './index.less'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

let uid = 0;

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
  };

  Menu = [];

  //查看图片对话框
  handleCancel = () => this.setState({ previewVisible: false });


  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };


  // 删除图片
  onRemove = (file) => {
    const { fileList, setFileList } = this.props
    setFileList(fileList.filter((item) => item.uid !== file.uid))
  };

  // 封面上传部分
  beforeUpload = (file) => {
    const mimeType = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp'];
    const isJPG = mimeType.includes(file.type);
    if (!isJPG) {
      message.error('您只能上传图片类型为jpg、png、bmp、webp、gif的图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 4;
    if (!isLt2M) {
      message.error('图片大小必须小于4M！');
    }
    return isJPG && isLt2M;
  };

  // 自定义封面上传
  handleCustomRequest = (options) => {
    const { fileList, setFileList } = this.props;
    // this.setState({ uploadPicLoading: true });
    const Name = options.file.name.slice(0, options.file.name.indexOf('.'));
    const ExtName = options.file.name.slice(options.file.name.lastIndexOf('.'));
    oss.ucuxin.uploader(
      {
        options,
        attachmentStr: `{"Path":"","AttachType":1,"Name":'${Name}',"ExtName":'${ExtName}',"ResizeMode":1,"SImgResizeMode":2,"CreateThumb":true}`,
        autoResizeLargeImage: true,
      },
      (res) => {
        if (res.Ret === 0) {
          // setImg(res.Data.Url);
          const newFileList = [].concat(fileList);
          uid = uid - 1;
          newFileList.push({
            uid: String(uid),
            name: res.Data.Name,
            status: 'done',
            url: res.Data.ThumbUrl,
            Width: res.Data.Width,
            Height: res.Data.Height,
            OriginalUrl: res.Data.Url,
          });
          setFileList(newFileList)

        } else {
          message.error('上传失败！');
        }
      },
    );
  };

  // 拖动排序
  allowDrop = ev => {
    ev.preventDefault();
  };

  drag = (ev, divdom, num) => {
    this.srcdiv = divdom;
    this.index = num;
    // ev.dataTransfer.setData("text/html", divdom.innerHTML);
  };

  drop = (ev, divdom, num) => {
    const { fileList, setFileList } = this.props;
    ev.preventDefault();
    if (this.srcdiv !== divdom) {
      // this.srcdiv.innerHTML = divdom.innerHTML;
      // divdom.innerHTML = ev.dataTransfer.getData("text/html");
      let data = [].concat(fileList);
      data[this.index].SNO = num;
      data[num].SNO = this.index;
      //   data.splice(this.index, 1, ...data.splice(num, 1, data[this.index]));
      if (this.index > num) {
        data.splice(num, 0, data[this.index]);
        data.splice(this.index + 1, 1);
      } else {
        data.splice(num + 1, 0, data[this.index])
        data.splice(this.index, 1);
      }
      setFileList(data)
    }
  };

  imgchange = (value) => {
    this.setState({
      previewVisible: true,
      previewImage: value.OriginalUrl
    })
  }

  render() {
    const { fileList, isDetails } = this.props;
    const { previewVisible, previewImage, previewTitle } = this.state;
    console.log(fileList)
    return (
      <div className={sty.warp}>
        <Upload
          // listType="picture"
          // fileList={fileList}
          //   onChange={this.handleChange}
          disabled={isDetails}
          onPreview={this.handlePreview}
          onRemove={this.onRemove}
          beforeUpload={this.beforeUpload}
          customRequest={this.handleCustomRequest}
          accept="image/gif,image/png,image/jpeg,image/bmp,image/webp"
        >
          <Button icon={<UploadOutlined />}>上传图片</Button>
        </Upload>
        <div>
          {
            fileList.map((item, k) => (
              <div
                key={k}
                className={sty.image_warp}
                ref={e => (this.Menu[k] = e)}
                draggable="true"
                onDragOver={this.allowDrop}
                onDrop={e => this.drop(e, this.Menu[k], k)}
                onDragStart={e => this.drag(e, this.Menu[k], k)}
              >
                {
                  !isDetails ? <span onClick={() => this.onRemove(item)}>x</span> : ''
                }
                <img src={item.url} alt='' className={sty.imagesItem} onClick={() => this.imgchange(item)} />
              </div>
            ))
          }
        </div>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
          width={800}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default PicturesWall;
